/**
 * 121. 买卖股票的最佳时机
 * https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock/
 */

/**
 * @param {number[]} prices
 * @return {number}
 */
function maxProfit(prices) {
  let min = prices[0];
  let max = min;
  let profit = 0;
  for (let i = 1; i < prices.length; i += 1) {
    const price = prices[i];
    if (price > max) {
      max = price;
      profit = Math.max(profit, max - min);
      continue;
    }
    if (price < min) {
      min = price;
      max = min;
    }
  }
  return profit;
}

console.log(maxProfit([7, 1, 5, 3, 6, 4]) === 5);
console.log(maxProfit([7, 6, 4, 3, 1]) === 0);
